package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;
import com.conversationboard.tree.Folders;
import com.conversationboard.tree.Node;

@WebServlet(name = "AdminMoveLinkControllerServlet", urlPatterns = "/Admin/AdminMoveLinkControllerServlet")
public class AdminMoveLinkControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -1913760589127058049L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = User.get(request.getUserPrincipal().getName());

			if ((!user.isSiteAdmin()) || (!SecurityChecks.passes(request, user, this))) {
				return;
			}

			int nodeId = Integer.parseInt(request.getParameter("nodeId"));
			int parentFolderId = Integer.parseInt(request.getParameter("parentFolder"));
			boolean moveLink = false;

			if (request.getParameter("move") != null) {
				moveLink = true;
			}

			/*
			 * If we want to remove all other instances of this board when
			 * moving, then find and delete all other instances first.
			 */

			Node originalLink = Folders.getInstance().getRoot().findNode(nodeId);

			if (moveLink) {
				Folders.getInstance().getRoot().removeChildNode(user, nodeId, true);
			}

			Node parentFolder = Folders.getInstance().getRoot().findFolder(parentFolderId);
			parentFolder.addChildNode(originalLink);

			Folders.getInstance().store();

			response.sendRedirect(Configuration.getInstance().getRoot() + "/Pages/Admin/boardstructure.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}